#!/usr/bin/env node
var program = require('commander');
let Option = program.Option;

function myParseInt(value, dummyPrevious){
    let val = parseInt(value, 10);
    if(isNaN(val)){
        throw new program.InvalidArgumentError('not a number');
    }
    return val;
}

function increaseVerbosity(value, prev){
    return prev+1;
}

function collect(value, prev){
    return prev.concat([value]);
}

function commaSeparatedList(value, prev){
    return value.split(',');
}

program.addOption(new Option('-s , --secret').hideHelp())
.addOption(new Option('-t, --timeout <delay>, timeout in seconds').default(60, 'one minute'))
.option('-f, --float <number>', 'float argument', parseFloat)
.option('-i, --integer <number>', 'integer argument', myParseInt)
.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
.option('-c, --collect <value>', 'repeatable value', collect, [])
.option('-l, --list <items>', 'comma separated list', commaSeparatedList);

//子命令：绑定函数方式实现
program.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination)=>{
    console.log(`clone command called`);
})

program.parse();

let options = program.opts();
if(options.float){
    console.log(`float: ${options.float}`);
}
if(options.integer){
    console.log(`float: ${options.integer}`);
}
if(options.verbose>0){
    console.log(`verbosity: ${options.verbose}`);
}

if(options.collect.length>0){
    console.log('options.collect:');
    console.log(options.collect);
}

if(options.list){
    console.log('options.list:');
    console.log(options.list);
}